#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试层次化输出效果
"""

import requests
import json
import time

def test_hierarchical_output():
    """测试层次化输出效果"""
    
    # 测试问题
    test_questions = [
        "什么是Rust的所有权系统？",
        "如何正确使用Rust的借用检查器？",
        "Rust中的生命周期是什么？",
        "Rust和C++在内存管理上有什么区别？",
        "Rust中如何处理错误？"
    ]
    
    print("🚀 开始测试层次化输出效果...")
    print("=" * 60)
    
    for i, question in enumerate(test_questions, 1):
        print(f"\n📝 测试问题 {i}: {question}")
        print("-" * 40)
        
        try:
            # 发送请求
            response = requests.post(
                'http://localhost:5001/api/chat',
                headers={
                    'Content-Type': 'application/json',
                    'X-API-Key': 'your-gemini-api-key'  # 替换为实际的API Key
                },
                json={
                    'message': question,
                    'user_id': 'test_user'
                },
                timeout=30
            )
            
            if response.status_code == 200:
                result = response.json()
                
                if result.get('success'):
                    answer = result.get('answer', '')
                    
                    # 检查层次化结构
                    print("✅ 回答结构分析:")
                    
                    # 检查一级标题
                    if '# ' in answer:
                        print("  ✓ 包含一级标题")
                        titles = [line.strip() for line in answer.split('\n') if line.strip().startswith('# ')]
                        for title in titles:
                            print(f"    - {title}")
                    else:
                        print("  ❌ 缺少一级标题")
                    
                    # 检查二级标题
                    if '## ' in answer:
                        print("  ✓ 包含二级标题")
                        subtitles = [line.strip() for line in answer.split('\n') if line.strip().startswith('## ')]
                        for subtitle in subtitles:
                            print(f"    - {subtitle}")
                    else:
                        print("  ❌ 缺少二级标题")
                    
                    # 检查代码块
                    if '```rust' in answer:
                        print("  ✓ 包含Rust代码示例")
                    else:
                        print("  ❌ 缺少Rust代码示例")
                    
                    # 检查Mermaid图表
                    if '```mermaid' in answer:
                        print("  ✓ 包含Mermaid图表")
                    else:
                        print("  ❌ 缺少Mermaid图表")
                    
                    # 检查表格
                    if '|' in answer and '---' in answer:
                        print("  ✓ 包含表格")
                    else:
                        print("  ❌ 缺少表格")
                    
                    # 检查列表
                    if '- ' in answer or '1. ' in answer:
                        print("  ✓ 包含列表")
                    else:
                        print("  ❌ 缺少列表")
                    
                    print(f"\n📊 回答长度: {len(answer)} 字符")
                    
                else:
                    print(f"❌ 请求失败: {result.get('error', '未知错误')}")
                    
            else:
                print(f"❌ HTTP错误: {response.status_code}")
                
        except requests.exceptions.Timeout:
            print("❌ 请求超时")
        except requests.exceptions.RequestException as e:
            print(f"❌ 请求异常: {e}")
        except Exception as e:
            print(f"❌ 其他错误: {e}")
        
        # 等待一下再发送下一个请求
        if i < len(test_questions):
            time.sleep(2)
    
    print("\n" + "=" * 60)
    print("🎉 层次化输出测试完成！")
    print("\n📋 测试总结:")
    print("- 检查了5个不同类型的Rust问题")
    print("- 验证了层次化标题结构")
    print("- 确认了多模态内容（代码、图表、表格）")
    print("- 评估了回答的完整性和结构性")

def test_specific_hierarchy():
    """测试特定的层次化结构"""
    
    print("\n🔍 测试特定层次化结构...")
    print("=" * 60)
    
    # 测试概念定义类问题
    question = "什么是Rust的trait？"
    
    try:
        response = requests.post(
            'http://localhost:5001/api/chat',
            headers={
                'Content-Type': 'application/json',
                'X-API-Key': 'your-gemini-api-key'
            },
            json={
                'message': question,
                'user_id': 'test_user'
            },
            timeout=30
        )
        
        if response.status_code == 200:
            result = response.json()
            
            if result.get('success'):
                answer = result.get('answer', '')
                
                print(f"📝 问题: {question}")
                print("\n📄 完整回答:")
                print("-" * 40)
                print(answer)
                print("-" * 40)
                
                # 详细分析层次结构
                print("\n🔍 层次结构分析:")
                
                lines = answer.split('\n')
                hierarchy_level = 0
                
                for line in lines:
                    line = line.strip()
                    if line.startswith('# '):
                        hierarchy_level = 1
                        print(f"  {'  ' * (hierarchy_level-1)}📚 {line[2:]}")
                    elif line.startswith('## '):
                        hierarchy_level = 2
                        print(f"  {'  ' * (hierarchy_level-1)}📖 {line[3:]}")
                    elif line.startswith('### '):
                        hierarchy_level = 3
                        print(f"  {'  ' * (hierarchy_level-1)}📝 {line[4:]}")
                    elif line.startswith('- **') and hierarchy_level > 0:
                        print(f"  {'  ' * hierarchy_level}• {line[4:]}")
                    elif line.startswith('1. **') and hierarchy_level > 0:
                        print(f"  {'  ' * hierarchy_level}① {line[4:]}")
                
                print(f"\n📊 统计信息:")
                print(f"  - 总行数: {len(lines)}")
                print(f"  - 一级标题: {len([l for l in lines if l.strip().startswith('# ')])}")
                print(f"  - 二级标题: {len([l for l in lines if l.strip().startswith('## ')])}")
                print(f"  - 三级标题: {len([l for l in lines if l.strip().startswith('### ')])}")
                print(f"  - 代码块: {answer.count('```rust')}")
                print(f"  - Mermaid图表: {answer.count('```mermaid')}")
                print(f"  - 表格: {answer.count('|') // 3}")  # 粗略估计
                
            else:
                print(f"❌ 请求失败: {result.get('error', '未知错误')}")
                
        else:
            print(f"❌ HTTP错误: {response.status_code}")
            
    except Exception as e:
        print(f"❌ 测试失败: {e}")

if __name__ == "__main__":
    print("🎯 Rust知识解释智能体 - 层次化输出测试")
    print("=" * 60)
    
    # 运行测试
    test_hierarchical_output()
    test_specific_hierarchy()
    
    print("\n✨ 所有测试完成！")
    print("\n💡 提示:")
    print("- 确保后端服务正在运行 (python app.py)")
    print("- 确保Gemini API Key已正确配置")
    print("- 检查网络连接是否正常") 